<script setup>
import { ref, computed } from 'vue'
import { addProjectService, updateProjectService } from '@/api/project.js'
import { Delete } from '@element-plus/icons-vue'
import ProjectTypeSelect from './ProjectTypeSelect.vue'

// 控制抽屉的显示与隐藏
const visibleDrawer = ref(false)

const defaultDTO = {
  name: null, // 服务项目名称
  projectTypeId: null, // 服务项目类型id
  price: null, // 服务项目价格
  description: null, // 服务项目描述
  projectItems: [] // 服务项目物品关联信息
}

const projectDTO = ref({ ...defaultDTO })

// 价格转换
const priceConverter = computed({
  get() {
    if (projectDTO.value.price) {
      return projectDTO.value.price / 100
    } else {
      return null
    }
  },
  set(value) {
    projectDTO.value.price = value * 100
  }
})

// 向外暴露方法
const open = (row) => {
  visibleDrawer.value = true // 打开抽屉
  if (row.id) {
    projectDTO.value = {
      id: row.id,
      name: row.name,
      projectTypeId: row.projectTypeId,
      price: row.price,
      description: row.description,
      projectItems: row.projectItems
    }
  } else {
    projectDTO.value = {
      ...defaultDTO,
      projectItems: [] // 清空物品关联信息
    }
  }
}

// 提交逻辑
const emit = defineEmits(['success'])
const handleSubmit = async () => {
  if (projectDTO.value.id) {
    await updateProjectService(projectDTO.value)
    ElNotification({
      title: '修改成功',
      type: 'success'
    })
  } else {
    await addProjectService(projectDTO.value)
    ElNotification({
      title: '新增成功',
      type: 'success'
    })
  }
  visibleDrawer.value = false
  projectDTO.value = { ...defaultDTO } // 提交后重置
  emit('success')
}

// 取消逻辑
const handleCancel = () => {
  visibleDrawer.value = false
  projectDTO.value = { ...defaultDTO }
}

const projectItemsEditRef = ref()
// 点击新增服务项目物品关联信息
const handleAddRelated = () => {
  projectItemsEditRef.value.open('选择与服务项目关联的物品')
}

// 删除服务项目物品关联信息
const handleProjectItemsDelete = (row) => {
  projectDTO.value.projectItems = projectDTO.value.projectItems.filter(
    (item) => item.itemId !== row.itemId
  )
}

// 处理新增服务项目物品关联信息
const handleAddProjectItems = (items) => {
  const itemsToAdd = items.map((item) => ({
    itemId: item.id,
    quantity: 0
  }))
  // 过滤已存在的 itemId
  const newItems = itemsToAdd.filter(
    (newItem) =>
      !projectDTO.value.projectItems.some((existing) => existing.itemId === newItem.itemId)
  )
  projectDTO.value.projectItems.push(...newItems)
}

// 显示物品信息
const activeItemId = ref() // 当前需要显示的物品ID
const showItemInfoForm = (itemId) => {
  activeItemId.value = itemId
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer v-model="visibleDrawer" :title="projectDTO.id ? '修改服务项目信息' : '新增服务项目'">
    <el-form :model="projectDTO" ref="formRef" label-width="auto">
      <el-form-item label="服务项目名称" prop="name">
        <el-input v-model="projectDTO.name" placeholder="请输入服务项目名称"></el-input>
      </el-form-item>
      <el-form-item label="服务项目类型" prop="projectTypeId">
        <project-type-select v-model="projectDTO.projectTypeId" width="100%" />
      </el-form-item>
      <el-form-item label="服务项目价格" prop="price">
        <el-input-number
          v-model="priceConverter"
          placeholder="请输入服务项目价格(元/项)"
          :min="0"
          :precision="2"
          :step="0.1"
          style="width: 280px"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="服务项目描述" prop="description">
        <el-input v-model="projectDTO.description" placeholder="请输入服务项目描述"></el-input>
      </el-form-item>
      <el-form-item label="服务项目-物品关联信息">
        <el-button type="primary" plain @click="handleAddRelated">选择物品</el-button>
      </el-form-item>
      <el-form-item>
        <el-table :data="projectDTO.projectItems" :border="true">
          <el-table-column prop="itemId" label="物品id">
            <template #default="{ row }">
              <el-popover effect="light" trigger="click" placement="left" :width="600">
                <template #reference>
                  <el-tag @click="showItemInfoForm(row.itemId)">{{ row.itemId }}</el-tag>
                </template>
                <ItemInfoForm v-if="activeItemId === row.itemId" :itemId="row.itemId" />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="物品数量">
            <template #default="{ row }">
              <el-input-number v-model="row.quantity" :min="0" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button
                type="danger"
                :icon="Delete"
                plain
                size="small"
                @click="handleProjectItemsDelete(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="handleSubmit">提交</el-button>
        <el-button type="info" plain @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
  <ItemSelect ref="projectItemsEditRef" @add="handleAddProjectItems"></ItemSelect>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 100px;
      height: 100px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      text-align: center;
    }
  }
}
</style>
